﻿using System;
using System.Configuration;

namespace Components.Configuration
{
  internal class FieldReferenceCollection : ConfigurationElementCollection
  {
    public override ConfigurationElementCollectionType CollectionType
    {
      get { return ConfigurationElementCollectionType.BasicMap; }
    }

    public FieldReference this[Int32 index]
    {
      get { return (FieldReference)BaseGet(index) ?? new FieldReference(); }
      set
      {
        if (BaseGet(index) != null)
        {
          BaseRemoveAt(index);
        }
        BaseAdd(index, value);
      }
    }

    public new FieldReference this[String key]
    {
      get
      {
        foreach (FieldReference fieldReference in this)
        {
          if (fieldReference.Key == key.ToLowerInvariant())
          {
            return fieldReference;
          }
        }
        return null;
      }
      set
      {
        String locatedKey = null;
        foreach (FieldReference fieldReference in this)
        {
          if (fieldReference.Key == key)
          {
            locatedKey = fieldReference.Key;
            break;
          }
        }
        if (!String.IsNullOrEmpty(locatedKey))
        {
          this[locatedKey] = value;
        }
      }
    }

    protected override ConfigurationElement CreateNewElement()
    {
      return new FieldReference();
    }

    protected override Object GetElementKey(ConfigurationElement fieldReference)
    {
      return ((FieldReference)fieldReference).Name;
    }

    protected override string ElementName
    {
      get { return "fieldReference"; }
    }
  }
}